package com.hw.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hw.shortlink.admin.common.biz.user.UserContext;
import com.hw.shortlink.admin.common.convention.exception.ClientException;
import com.hw.shortlink.admin.dao.entity.Group;
import com.hw.shortlink.admin.dao.mapper.GroupMapper;
import com.hw.shortlink.admin.dto.req.GroupSaveReqDto;
import com.hw.shortlink.admin.dto.req.GroupSortReqDto;
import com.hw.shortlink.admin.dto.req.GroupUpdateReqDto;
import com.hw.shortlink.admin.dto.resp.GroupQueryRespDto;
import com.hw.shortlink.admin.remote.dto.ShortLinkRemoteService;
import com.hw.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDto;
import com.hw.shortlink.admin.service.GroupService;
import com.hw.shortlink.admin.until.RandomGenerator;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements GroupService {

    private final ShortLinkRemoteService shortLinkRemoteService=new ShortLinkRemoteService() {
    };

    @Override
    public void createGroup(GroupSaveReqDto groupSaveReqDto) {
        createGroup(UserContext.getUsername(),groupSaveReqDto);
    }

    @Override
    public void createGroup(String username, GroupSaveReqDto groupSaveReqDto) {
        String gid;
        do {
            gid = RandomGenerator.generateRandom();

        } while (!availableGid(username,gid));
        //todo 通过缓存每个用户的分组数量限制最大分组数量
        Group group = Group.builder()
                .name(groupSaveReqDto.getName())
                .username(username)
                .sortOrder(0)
                .gid(gid)
                .build();

        save(group);
    }

    @Override
    public List<GroupQueryRespDto> listGroup() {

        List<Group> groups = lambdaQuery()
                .eq(Group::getUsername, UserContext.getUsername())
                .eq(Group::getDelFlag,0)
                .orderByDesc(List.of(Group::getSortOrder, Group::getUpdateTime))
                .list();

        List<ShortLinkGroupCountQueryRespDto> countList = shortLinkRemoteService
                .listGroupShortLinkCount(groups.stream().map((Group::getGid)).toList()).getData();

        //转换成gid->count的map
        Map<String, Integer> map = countList.stream()
                .collect(Collectors.toMap(ShortLinkGroupCountQueryRespDto::getGid,
                        ShortLinkGroupCountQueryRespDto::getCount));

        List<GroupQueryRespDto> list = BeanUtil.copyToList(groups, GroupQueryRespDto.class);

        list.forEach((o1)->o1.setShortLinkCount(map.getOrDefault(o1.getGid(),0)));


        return list ;
    }

    @Override
    public void updateGroup(GroupUpdateReqDto groupUpdateReqDto) {

        String gid = groupUpdateReqDto.getGid();
        String name = groupUpdateReqDto.getName();

        boolean flag = lambdaUpdate()
                .eq(Group::getUsername,UserContext.getUsername())
                .eq(Group::getDelFlag,0)
                .eq(Group::getGid, gid)
                .set(Group::getName, name)
                .update();

        if(!flag){
            throw new ClientException("修改失败");
        }
    }

    @Override
    public void deleteByGid(String gid) {
        boolean flag = lambdaUpdate()
                .eq(Group::getUsername,UserContext.getUsername())
                .eq(Group::getDelFlag,0)
                .eq(Group::getGid, gid)
                .set(Group::getDelFlag, 1)
                .update();
        if(!flag){
            throw new ClientException("删除失败");
        }
    }

    @Override
    public void sortGroup(List<GroupSortReqDto> list) {
        list.forEach(groupSortReqDto -> lambdaUpdate()
                .set(Group::getSortOrder, groupSortReqDto.getSortOrder())
                .eq(Group::getUsername, UserContext.getUsername())
                .eq(Group::getDelFlag, 0)
                .eq(Group::getGid, groupSortReqDto.getGid())
                .update());
    }


    private boolean availableGid(String username,String gid) {
        Group group = lambdaQuery()
                .eq(Group::getGid, gid)
                .eq(Group::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername()))
                .eq(Group::getDelFlag, 0)
                .one();

        return group == null;
    }
}
